from datetime import datetime, timedelta
from flask import current_app, jsonify
from flask import g
from flask import redirect
from flask import render_template
from flask import request
from flask import session
from flask import url_for
from info.models import User, News, Category
from info.utils.response_code import RET
from . import admin_blu
from info.utils.commons import login_status
import time
from info import constants, db


@admin_blu.route('/index')
@login_status
def index():
    """后台管理首页"""
    user = g.user
    return render_template('admin/index.html', user=user.to_dict())


@admin_blu.route('/login', methods=['GET', 'POST'])
def login():
    # 1.判断请求方式是否为get，则使用session获取用户登录信息，user_id, is_admin
    if request.method == 'GET':
        user_id = session.get('user_id', None)
        is_admin = session.get('is_admin', False)
        # 判断session中的用户信息是否是管理员账户，如果是则跳转到后台页面
        if user_id and is_admin:
            # 为何使用重定向？因为要往页面中传入参数，需要视图函数中传入，所以重定向
            return redirect(url_for('admin.index'))
        return render_template('admin/login.html')

    # 2.请求方式为POST
    # 2.1.获取前端表单参数
    username = request.form.get('username')
    password = request.form.get('password')
    # 2.2.判断参数完整性
    if not all([username, password]):
        return render_template('admin/login.html', errmsg='参数不完整')
    # 2.3.根据用户名查询数据库，判断用户是否存在
    try:
        user = User.query.filter(User.mobile == username, User.is_admin == True).first()
    except Exception as e:
        current_app.logger.error(e)
        return render_template('admin/login.html', errmsg='数据库查询错误')
    # 2.4.判断用户是否存在以及密码是否正确
    if not user or user.check_password(password):
        return render_template('admin/login.html', errmsg='用户名或密码错误')
    # 2.5.缓存用户信息
    session['user_id'] = user.id
    session['mobile'] = user.mobile
    session['nick_name'] = user.nick_name
    session['is_admin'] = user.is_admin
    # 2.6.跳转到后台管理页面
    return redirect(url_for('admin.index'))


@admin_blu.route('/user_count')
def user_count():
    # 查询总人数
    total_count = 0
    try:
        # 总人数即不是管理员的用户总和
        total_count = User.query.filter(User.is_admin == False).count()
    except Exception as e:
        current_app.logger.error(e)

    # 查询月新增数
    mon_count = 0
    t = time.localtime()
    # 生成月份开始日期的字符串
    mon_begin_date_str = "%d-%02d-01" % (t.tm_year, t.tm_mon)
    # 把日期字符串转换成日期对象
    mon_begin_date = datetime.strptime(mon_begin_date_str, "%Y-%m-%d")
    # 查询每月新增的人数
    try:
        mon_count = User.query.filter(User.is_admin == False, User.create_time > mon_begin_date).count()
    except Exception as e:
        current_app.logger.error(e)

    # 查询日新增数
    day_count = 0
    # 生成天开始时间的字符串
    day_begin_date_str = "%d-%02d-%02d" % (t.tm_year, t.tm_mon, t.tm_mday)
    # 把日期字符串转换成日期对象
    day_begin_date = datetime.strptime(day_begin_date_str, "%Y-%m-%d")
    # 查询每天新增的人数
    try:
        day_count = User.query.filter(User.is_admin == False, User.create_time > day_begin_date).count()
    except Exception as e:
        current_app.logger.error(e)

    # 定义活跃的人数 活跃的时间
    active_time = []
    active_count = []
    # 默认按照31天往前推
    active_begin_date_str = "%d-%02d-%02d" % (t.tm_year, t.tm_mon, t.tm_mday)
    active_begin_date = datetime.strptime(active_begin_date_str, "%Y-%m-%d")
    for x in range(0, 31):
        # 今天的0时0分
        begin_date = active_begin_date - timedelta(days=x)
        # 今天的24时，明天的0时0分
        end_date = active_begin_date - timedelta(days=(x - 1))
        # 把日期对象转换为字符串
        begin_date_str = datetime.strftime(begin_date, "%Y-%m-%d")
        count = 0
        try:
            count = User.query.filter(User.is_admin == False, User.last_login >= begin_date,
                                      User.last_login < end_date).count()
        except Exception as e:
            current_app.logger.error(e)
        # 添加日期和活跃人数
        active_time.append(begin_date_str)
        active_count.append(count)
    # 反转列表
    active_time.reverse()
    active_count.reverse()

    data = {
        'total_count': total_count,
        'mon_count': mon_count,
        'day_count': day_count,
        'active_time': active_time,
        'active_count': active_count
    }

    return render_template('admin/user_count.html', data=data)


@admin_blu.route('/user_list')
def user_list():
    # 1.获取参数
    page = request.args.get('p', '1')
    # 2.校验参数
    try:
        page = int(page)
    except Exception as e:
        current_app.logger.error(e)
        page = 1
    # 3.查询数据库
    users = []
    follows = []
    current_page = 1
    total_page = 1
    try:
        paginate = User.query.filter(User.is_admin == False).paginate(page, constants.ADMIN_USER_PAGE_MAX_COUNT, False)
        current_page = paginate.page
        total_page = paginate.pages
        users = paginate.items
    except Exception as e:
        current_app.logger.error(e)
        # 返回json数据没有意思，因为目前是通过传递数据给模板
        # return jsonify(errno=RET.DBERR, errmsg='查询数据错误')
    # 4.定义容器遍历查询结果
    user_dict_list = []
    for user in users:
        user_dict_list.append(user.to_admin_dict())
    data = {
        'users': user_dict_list,
        'current_page': current_page,
        'total_page': total_page
    }
    return render_template('admin/user_list.html', data=data)


@admin_blu.route('/news_review')
def news_review():
    # 1.获取参数 页数p 默认1 关键字参数keywords 默认None
    page = request.args.get('p', 1)
    keywords = request.args.get('keywords', None)
    # 2.校验参数 页码应是int
    try:
        page = int(page)
    except Exception as e:
        current_app.logger.error(e)
        page = 1

    news_list = []
    current_page = 1
    total_page = 1

    filters = [News.status != 0]
    # 判断关键字是否存在
    if keywords:
        # 存在则添加关键字搜索
        filters.append(News.title.contains(keywords))
    # 查询数据库
    try:
        paginate = News.query.filter(*filters).order_by(News.create_time.desc()) \
            .paginate(page, constants.ADMIN_NEWS_PAGE_MAX_COUNT, False)
        news_list = paginate.items
        current_page = paginate.page
        total_page = paginate.pages
    except Exception as e:
        current_app.logger.error(e)

    # 定义容器存储新闻的字典格式数据
    news_dict_list = []
    for new in news_list:
        news_dict_list.append(new.to_review_dict())
    data = {
        'news_list': news_dict_list,
        'current_page': current_page,
        'total_page': total_page
    }

    return render_template('admin/news_review.html', data=data)


@admin_blu.route('/news_review_detail/<int:news_id>')
def news_review_detail(news_id):
    # 根据news_id查询数据库
    news = None
    try:
        news = News.query.get(news_id)
    except Exception as e:
        current_app.logger.error(e)
    # 判断查询结果
    if not news:
        return render_template('admin/news_review_detail.html', data={'errmsg': '未查到数据'})
    # 查询结果存在
    data = {
        'news': news.to_dict()
    }
    # 返回给模板
    return render_template('admin/news_review_detail.html', data=data)


@admin_blu.route('/news_review_action', methods=['POST'])
def news_review_action():
    # 1.获取参数：news_id/action
    news_id = request.json.get('news_id')
    action = request.json.get('action')
    # 2.校验参数
    if not all([news_id, action]):
        return jsonify(errno=RET.PARAMERR, errmsg='参数不完整')
    if action not in ['accept', 'reject']:
        return jsonify(errno=RET.PARAMERR, errmsg='参数格式错误')

    # 3.查询新闻数据
    try:
        new = News.query.get(news_id)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg='数据查询失败')
    if not new:
        return jsonify(errno=RET.NODATA, errmsg='未查询到数据')

    # 4.判断新闻审核结果
    if action == 'accept':
        # 审核通过
        new.status = 0
    else:
        # 审核未通过，需说明不通过原因
        reason = request.json.get('reason')
        if not reason:
            return jsonify(errno=RET.PARAMERR, errmsg='请输入拒绝原因')
        new.status = -1
        new.reason = reason

    # 5.将新闻审核结果存入数据库
    try:
        db.session.add(new)
        db.session.commit()
    except Exception as e:
        current_app.logger.error(e)
        db.session.rollback()
        return jsonify(errno=RET.DBERR, errmsg='数据保存失败')

    # 6.返回结果
    return jsonify(errno=RET.OK, errmsg='审核完成')


@admin_blu.route('/news_edit')
def news_edit():
    # 1.获取参数 页数 默认1 关键词 keywords 默认None
    page = request.args.get('p', '1')
    keywords = request.args.get('keywords', None)
    # 2.校验参数
    try:
        page = int(page)
    except Exception as e:
        current_app.logger.error(e)
    # 3.初始化变量news_list=[] current_page=1 total_page=1
    news_list = []
    current_page = 1
    total_page = 1
    # 4.定义过滤条件filters filter[News.status!=0] 如果关键词存在则添加到过滤条件中
    filters = [News.status != 0]
    if keywords:
        filters.append(News.title.contains(keywords))
    # 5.查询新闻数据库 默认按新闻发布时间排序 分页查询
    try:
        paginate = News.query.filter(*filters).order_by(News.create_time.desc()) \
            .paginate(page, constants.ADMIN_NEWS_PAGE_MAX_COUNT, False)
        current_page = paginate.page
        total_page = paginate.pages
        news_list = paginate.items
    except Exception as e:
        current_app.logger.error(e)

    # 定义容器 并遍历新闻查询结果 转成字典存入容器中
    news_dict_list = []
    for new in news_list:
        news_dict_list.append(new.to_basic_dict())
    # 准备data数据并返回给模板
    data = {
        'news_list': news_dict_list,
        'current_page': current_page,
        'total_page': total_page
    }

    return render_template('admin/news_edit.html', data=data)


@admin_blu.route('/news_type')
def news_type():
    # 1.定义查询新闻分类过滤规则
    # filters = [Category.id > 1]
    # 2.根据过滤条件进行查询
    category_list = []
    try:
        # category_list = Category.query.filter(*filters).all()
        category_list = Category.query.all()
    except Exception as e:
        current_app.logger.error(e)
    # 3.定义容器
    category_dict_list = []
    # 4.遍历新闻分类查询结果 并转成字典存进容器中
    for category in category_list:
        category_dict_list.append(category.to_dict())
    category_dict_list.pop(0)
    # 5.组织data数据
    data = {
        'category_list': category_dict_list
    }

    return render_template('admin/news_type.html', data=data)


@admin_blu.route('/add_modify', methods=['POST'])
def add_modify():
    # 1.获取参数
    category_id = request.json.get('id')
    category_name = request.json.get('name')
    # 2.判断参数是否存在
    if not category_name:
        return jsonify(errno=RET.PARAMERR, errmsg='参数不完整')
    # 3.判断分类id是否存在
    if category_id:
        try:
            category = Category.query.get(category_id)
        except Exception as e:
            current_app.logger.error(e)
            return jsonify(errno=RET.DBERR, errmsg='数据查询失败')

        if not category:
            return jsonify(errno=RET.NODATA, errmsg='未查询到分类数据')

        category.name = category_name
    else:
        category = Category()
        category.name = category_name

    try:
        db.session.add(category)
        db.session.commit()
    except Exception as e:
        current_app.logger.error(e)
        db.session.rollback()
        return jsonify(errno=RET.DBERR, errmsg='保存数据失败')

    return jsonify(errno=RET.OK, errmsg='操作成功')
